package com.example.chinawenddingexpo.service;

import com.example.chinawenddingexpo.model.User;
import com.example.chinawenddingexpo.repository.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Optional;

@Service
public class UserService {

	// 自动注入UserRepository
	@Autowired
	private UserRepository userRepository;

	// 微信小程序登录
	public User wxLogin(String openid, String nickname, String avatarUrl, Integer gender) {
		User user = getUserByOpenid(openid);
		
		if (user == null) {
			// 新用户注册
			user = new User();
			user.setOpenid(openid);
			user.setNickname(nickname);
			user.setAvatarUrl(avatarUrl);
			user.setGender(gender);
		} else {
			// 更新用户信息
			user.setNickname(nickname);
			user.setAvatarUrl(avatarUrl);
			user.setGender(gender);
		}
		
		return saveOrUpdate(user);
	}

	// 根据用户ID查询用户
	public User getUserById(Long userId) {
		Optional<User> user = userRepository.findById(userId);
		return user.orElse(null);
	}

	// 根据openid查询用户
	public User getUserByOpenid(String openid) {
		Optional<User> user = userRepository.findByOpenid(openid);
		return user.orElse(null);
	}

	// 保存或更新用户
	public User saveOrUpdate(User user) {
		return userRepository.save(user);
	}
}